let controller: AbortController;

export const stopStream = () => {
  controller?.abort();
};

// 获取后端返回的数据流
export const httpStream = async (props: {
  url?: string;
  method?: string;
  body?: object;
  handleNewToken?: (newToken: string) => void;
}) => {
  controller = new AbortController();
  const { url, method = "POST", body = {} } = props;
  try {
    const res = await fetch(url ?? "https://api.transuncle.cn/ai/chat", {
      method,
      headers: {
        "Content-Type": "application/json",
        "Accept": "text/event-stream"
      },
      body: JSON.stringify(body),
      signal: controller.signal,
    });

    if (res.ok) {
      const reader = res.body?.getReader();
      const decoder = new TextDecoder();

      while (true) {
        const content = await reader?.read();
        if (!content || !content.value) {
          break;
        }
        const text = decoder.decode(content.value, { stream: true });

        // 处理每一行数据
        const lines = text.split('\n');
        for (const line of lines) {
          if (line.startsWith('data: ')) {
            const data = line.substring(6); // 移除 "data: " 前缀
            try {
              // 尝试解析为对象
              const result = JSON.parse(data);
              console.log("收到响应:", result);
              props.handleNewToken?.(data);
            } catch {
              console.log("原始响应:", data);
              props.handleNewToken?.(data);
            }
          }
        }
      }
    } else if (res.status === 401) {
      throw new Error("未授权访问");
    } else {
      throw new Error("流数据错误");
    }
  } catch (error) {
    console.error("流式请求失败:", error);
    throw error;
  }
};